package com.lanou3g.dllo.baidumusic.musiclibrary.playlist;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;

/**
 * Created by dllo on 16/6/21.
 */
public class PlaylistGsonRequest<T> extends Request<T> {

    private Response.Listener<T> mListener;
    private Class<T> clazz;


    public PlaylistGsonRequest(int method, String url, Response.Listener<T> listener, Response.ErrorListener errorListener, Class<T> clazz) {
        super(method, url, errorListener);
        mListener = listener;
        this.clazz = clazz;
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        String parsed;
        T t = null;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            Gson gson = new Gson();
            t = gson.fromJson(parsed, clazz);
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return Response.success(t, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(T response) {
        mListener.onResponse(response);
    }
}
